<?php

namespace App\Http\Controllers\Service;

use App\Http\Controllers\Controller;
use App\Models\Material;
use Intervention\Image\Facades\Image;

class KindeditorController extends Controller
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(){

        $dir = $this->request->get('dir');

        if ($file = $this->request->file('imgFile')){
            if ($dir === 'image') {
                $img = Image::make($file->getRealPath());
                $image = [
                    'uid'=>$this->uid,
                    'username'=>$this->username,
                    'type'=>'image',
                    'created_at'=>time(),
                    'updated_at'=>time(),
                    'extension'=>$file->extension(),
                    'size'=>$file->getSize(),
                    'name'=>$file->getClientOriginalName(),
                    'width'=>$img->width(),
                    'height'=>$img->height()
                ];

                $filename  = $file->hashName();
                $imagePath = 'image/'.date('Y').'/'.date('m').'/'.$filename;
                $thumbPath = 'thumb/'.date('Y').'/'.date('m').'/'.$filename;

                //大图
                if ($img->getWidth() > 1600) {
                    $scale = 1600/$img->getWidth();
                    @mkdir(dirname(storage_public_path($imagePath)), 0777, true);
                    $img->resize(1600, $img->getHeight()*$scale)->save(storage_public_path($imagePath));
                } else {
                    $img->save(storage_public_path($imagePath));
                }

                //缩略图
                if ($img->getWidth() > 500){
                    $scale = 500/$img->getWidth();
                    @mkdir(dirname(storage_public_path($thumbPath)), 0777, true);
                    $img->resize(500, $img->getHeight()*$scale)->save(storage_public_path($thumbPath));
                } else {
                    $img->save(storage_public_path($thumbPath));
                }

                $image['source'] = $imagePath;
                $image['thumb'] = $thumbPath;

                $image['id'] = Material::insertGetId($image);
                $image['image'] = $imagePath;
                $image['imageurl'] = image_url($imagePath);
                $image['thumburl'] = image_url($thumbPath);

                return response()->json([
                    'error'=>0,
                    'url'=>image_url($imagePath)
                ]);
            }else {

                $extension = $file->extension();
                $material = [
                    'uid'=>$this->uid,
                    'username'=>$this->username,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                    'extension'=>$extension,
                    'size'=>$file->getSize(),
                    'name'=>$file->getClientOriginalName(),
                    'width'=>0,
                    'height'=>0
                ];

                if (in_array($extension, ['jpg','jpeg','gif','png','bmp'])){
                    $material['type'] = 'image';
                }elseif (in_array($extension, ['mp4','mpeg', 'mpg', 'rmvb', 'rm', 'avi', 'wmv'])){
                    $material['type'] = 'video';
                }elseif (in_array($extension, ['mp3', 'midi', 'wav'])){
                    $material['type'] = 'voice';
                }elseif (in_array($extension, ['doc', 'ppt', 'xls', 'docx', 'pptx', 'xlsx', 'pdf', 'txt'])){
                    $material['type'] = 'doc';
                }else {
                    $material['type'] = 'file';
                }

                $material['source'] = $file->store($material['type'].'/'.date('Y').'/'.date('m'));
                $material['id'] = Material::insertGetId($material);

                return response()->json([
                    'error'=>0,
                    'url'=>material_url($material['source'])
                ]);
            }
        }else {
            return response()->json([
                'error'=>1,
                'message'=>'file upload fail!'
            ]);
        }
    }

    public function manager(){

        $dir = $this->request->get('dir');

        $file_list = [];
        if ($dir === 'image') {
            Material::where('uid', $this->uid)->where('type', 'image')->orderByDesc('id')
                ->limit(100)->get()->map(function ($m) use (&$file_list){
                    $file_list[] = [
                    'is_dir'=>false,
                    'has_file'=>false,
                    'is_photo'=>true,
                    'filesize'=>$m->size,
                    'filetype'=>$m->extension,
                    'filename'=>$m->name,
                    'datetime'=>@date('Y-m-d H:i:s', $m->created_at),
                    'thumburl'=>image_url($m->thumb),
                    'url'=>image_url($m->source)
                ];
            });
        }

        if ($dir === 'media') {
            Material::where('uid', $this->uid)->whereIn('type', ['video', 'voice'])->orderByDesc('id')
                ->limit(100)->get()->map(function ($m) use (&$file_list){
                    $file_list[] = [
                        'is_dir'=>false,
                        'has_file'=>false,
                        'is_photo'=>false,
                        'filesize'=>$m->size,
                        'filetype'=>$m->extension,
                        'filename'=>$m->name,
                        'datetime'=>@date('Y-m-d H:i:s', $m->created_at),
                        'url'=>storage_url($m->source)
                    ];
                });
        }

        if ($dir === 'file') {
            Material::where('uid', $this->uid)->whereIn('type', ['doc', 'file'])->orderByDesc('id')
                ->limit(100)->get()->map(function ($m) use (&$file_list){
                    $file_list[] = [
                        'is_dir'=>false,
                        'has_file'=>false,
                        'is_photo'=>false,
                        'filesize'=>$m->size,
                        'filetype'=>$m->extension,
                        'filename'=>$m->name,
                        'datetime'=>@date('Y-m-d H:i:s', $m->created_at),
                        'url'=>storage_url($m->source)
                    ];
                });
        }

        return response()->json([
            'total_count'=>count($file_list),
            'file_list'=>$file_list,
            'current_url'=>storage_url('/'),
            'moveup_dir_path'=>'',
            'current_dir_path'=>''
        ]);
    }
}
